package com.kjzy.interceptor;

import com.kjzy.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器：拦截用户请求
//1.实现HandlerInterceptor接口
//2.（ctrl+o）重写三个方法
public class UserInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
//        登录相关操作不拦截，设置为true
        if(url.indexOf("admin_login")>=0||(url.indexOf("adminLogin.action")>=0)){
            return true;
        }
//        获取session
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("ADMIN_SESSION");
//       如果存在该用户，返回true则继续往下执行
        if(admin!=null){
            return  true;
        }
//        不符合条件的转发到登录页面
        request.setAttribute("msg","请先登录");
        request.getRequestDispatcher("WEB-INF/jsp/admin/admin_login.jsp").forward(request,response);
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
